package lxt.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import lxt.dao.ABseDao;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
/**
 * curd父类dao
 * @author Lit
 *
 */
public class ABseDaoImpl extends HibernateDaoSupport implements ABseDao {

	protected Logger logger = Logger.getLogger(this.getClass());

	@Resource
	public void setMyHibernateTemplate(HibernateTemplate myHibernateTemplate)
	{
		this.setHibernateTemplate(myHibernateTemplate);
	}

	public Session getHibernateSession()
	{
		return this.getSession();
	}

	public void save(Object object)
	{
		getHibernateTemplate().save(object);
	}

	public Object get(Class<?> clazz, Serializable id)
	{
		Object o = getHibernateTemplate().get(clazz, id);

		if (o == null)
		{
			System.out.println("查询结果是null");
		}

		return o;
	}

	public List<?> loadAll(Class<?> clazz)
	{
		return getHibernateTemplate().loadAll(clazz);
	}

	public void delete(Class<?> clazz, Serializable id)
	{
		getHibernateTemplate().delete(get(clazz, id));
	}

	public void update(Object object)
	{
		getHibernateTemplate().update(object);

	}

	/**
	 * 分页查询
	 * 
	 * @param hql
	 *            查询语句
	 * @param param
	 *            查询条件           
	 * @param offset
	 *            开始记录
	 * @param length
	 *            一次查询几条记录
	 * @return
	 */
	public List<?> queryForPage(final String hql,final ArrayList<Object> param,final int offset, final int length)
	{
		List<?> list = getHibernateTemplate().executeFind(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException, SQLException
			{
				Query query = session.createQuery(hql);
				//插入查询条件
				if(param.size()>0){
					for(int i=0;i<param.size();i++){
						query.setParameter(i, param.get(i));
					}
				}
				//设置分页
				query.setFirstResult(offset);
				query.setMaxResults(length);
				List<?> list = query.list();
				return list;
			}
		});
		return list;
	}

	/**
	 * 查询所有记录数
	 * 
	 * @return 总记录数
	 */
	public int getAllRowCount(String hql,ArrayList<Object> param)
	{
//		System.out.println(param.isEmpty());
//		if(param.isEmpty()){
//			return getHibernateTemplate().find(hql).size();
//		}
		return getHibernateTemplate().find(hql,param.toArray()).size();
	}
}
